// miniprogram/pages/home_center/common_panel/index.js.js
require('regenerator-runtime');
import {
  onDpDataChange,
  offDpDataChange,
  getDeviceInfo,
  publishDps,
} from '@ray-js/wechat';

import { 
  sendDeviceCommand,
  getDeviceDetailPage,
  log,
} from "../../../utils/api/common-api.js"


Page({
  /**
   * 页面的初始数据
   */
  data: {
    device_id: '',
    device_name: '',
    titleItem: {
      name: '',
      value: '',
    },
    devInfo: {
      name: '',
      iconUrl: '',
    },
    dps: {},
    roDpList: {}, //只上报功能点
    rwDpList: {}, //可上报可下发功能点
    isRoDpListShow: false,
    isRwDpListShow: false,
    forest: '../../image/forest@2x.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      device_id
    } = options;
    this.setData({
      device_id
    });

    // onDpDataChange(this.handleDpChange);
  },

  onUnload: function () {
    // offDpDataChange(this.handleDpChange);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: async function () {
    const {
      device_id
    } = this.data;
    const devInfo = await getDeviceDetailPage({
      device_id
    });
    console.log('devInfo:',devInfo)
    console.log('devInfo.schema:',JSON.stringify(devInfo.schema))
    console.log('devInfo.dpCodes:',JSON.stringify(devInfo.dpCodes))

    const {
      roDpList,
      rwDpList
    } = this.reducerDpList(
      devInfo.schema,
      devInfo.dpCodes
    );
    console.log(roDpList, rwDpList)
    // 获取头部展示功能点信息
    let titleItem = {
      name: '',
      value: '',
    };

    const roDpListLength = Object.keys(roDpList).length;
    const isRoDpListShow = Object.keys(roDpList).length > 0;
    const isRwDpListShow = Object.keys(rwDpList).length > 0;

    if (isRoDpListShow) {
      const code = Object.keys(roDpList)[0];
      titleItem = roDpList[code];
    } else if (isRwDpListShow) {
      const code = Object.keys(rwDpList)[0];
      titleItem = rwDpList[code];
    }
    console.log('titleItem', titleItem);
    if(!roDpList["air_quality"]) {
      roDpList["air_quality"] = {
        name:"空气质量"
      }
    }
    if( roDpList["pm25"].value < 90){
      roDpList["air_quality"].value = '优'
    }else if( roDpList["pm25"].value > 150){
      roDpList["air_quality"].value = '差'
    }else{
      roDpList["air_quality"].value = '良'
    }
    console.log('devInfo.isOnline',devInfo.isOnline)
    rwDpList['switchR'].value = devInfo.isOnline === false ? false : rwDpList['switchR'].value;
    delete roDpList["pm25"]

    this.setData({
      devInfo,
      titleItem,
      roDpList,
      rwDpList,
      isRoDpListShow,
      isRwDpListShow,
      roDpListLength,
    });
  },

  handleDpChange: function ({
    deviceId,
    dpsMapCode
  }) {
    const {
      device_id,
      roDpList,
      rwDpList,
      titleItem
    } = this.data;
    if (device_id === deviceId) {
      Object.keys(dpsMapCode).forEach((code) => {
        if (titleItem.code === code) {
          titleItem.value = dpsMapCode[code];
        }
        if (roDpList[code]) {
          roDpList[code].value = dpsMapCode[code];
        }
        if (rwDpList[code]) {
          rwDpList[code].value = dpsMapCode[code];
        }
      });
      this.setData({
        roDpList,
        rwDpList
      });
    }
  },

  // 分离只上报功能点，可上报可下发功能点
  reducerDpList: function (schema, dps) {
    // 处理功能点和状态的数据
    let roDpList = {};
    let rwDpList = {};
    if (schema.length) {
      schema.map((item) => {
        item.value = dps[item.code];
        if (item.mode !== 'ro') {
          rwDpList[item.code] = item;
        } else {
          roDpList[item.code] = item;
        }
      });
    }
    return {
      roDpList,
      rwDpList
    };
  },

  sendDp: async function (e) {
    let {
      dpCode,
      value
    } = e.detail;
    const {
      device_id
    } = this.data;
    console.log(device_id, dpCode, value, this.data.rwDpList)

    let rwDpList = {
      ...this.data.rwDpList
    }
    rwDpList[dpCode].value = value
    
    this.setData(this.data.rwDpList, rwDpList)
    console.log('rwDpList', rwDpList)
    console.log('this.data.rwDpList', this.data.rwDpList)
    dpCode = dpCode === "switchR" ? "switch" : dpCode;
    let dps = [{"code":dpCode,"value":value}]
    console.log(dps)
    log("下发设备指令:"+device_id, JSON.stringify(dps),'设备信息页面');
    try {
      const res = await sendDeviceCommand({
        device_id,
        dps,
      });
      console.log(res)
      if(res === 'false') {
        wx.showToast({
          title: '失败，检查设备',
          icon: 'error',
        })
      }
    } catch (error) {
      return wx.showToast({
        title: '失败，检查设备',
        icon: 'error',
      });
    }
  },

  jumpTodeviceEditPage: function () {
    const {
      device_id
    } = this.data;
    console.log('goto index')
    wx.navigateTo({
      url: `/pages/guide/index`,
    });
  },
  backPage: function () {
    console.log('backPage')
    wx.navigateBack({
      delta: 1
    });
  }
});